import cv2
import numpy as np

def addSalt(img, n):
    """
    给img添加 n 个 椒盐噪点
    :param img: 原始图
    :param n: 噪点数量
    :return: 返回结果图片
    """
    for k in range(0, n):
        # get the random point
        xi = int(np.random.uniform(0, img.shape[1]))
        xj = int(np.random.uniform(0, img.shape[0]))
        # add noise
        if img.ndim == 2:
            img[xj, xi] = 255
        elif img.ndim == 3:
            img[xj, xi, 0] = 25
            img[xj, xi, 1] = 20
            img[xj, xi, 2] = 20




if __name__ == '__main__':
    img = cv2.imread('imgs/Lena.jpg')
    cv2.imshow('img', img)

    # addSalt(img, 10000)
    # cv2.imshow('img', img)a

    img_noise = cv2.add
#均值滤波
    blur = cv2.blur(img, (3,3))
    cv2.imshow('blur', blur)

    #高斯滤波
    gauss = cv2.GaussianBlur(img, (3, 3), 0)
    cv2.imshow('GaussianBlur', gauss)

#中值滤波
    median = cv2.medianBlur(img, 3)
    cv2.imshow('medianBlur', median)

    NpKernel = np.uint8(np.zeros((5, 5)))
    for i in range(5):
        NpKernel[2, i] = 1
        NpKernel[i, 2] = 1

    element = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))


#形态学滤波, 先开后闭，去除噪声
    morphology_open = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel=element)
    morphology_close = cv2.morphologyEx(morphology_open, cv2.MORPH_CLOSE, kernel=element)
    cv2.imshow("open-close-morphology", morphology_close)

    cv2.waitKey()
